
package com.controller;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.entity.ShangjiaEntity;
import com.entity.ShangpinEntity;
import com.entity.view.ShangpinOrderView;
import com.entity.view.ShangpinView;
import com.service.DictionaryService;
import com.service.ShangjiaService;
import com.service.ShangpinOrderService;
import com.service.ShangpinService;
import com.utils.CommonUtil;
import com.utils.PageUtils;
import com.utils.PoiUtil;
import com.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URL;
import java.util.*;

/**
 * 商品
 */
@RestController
@Controller
@RequestMapping("/shangpin")
public class ShangpinController {

    private static final Logger logger = LoggerFactory.getLogger(ShangpinController.class);

    @Resource
    private ShangpinService shangpinService;

    @Resource
    private DictionaryService dictionaryService;

    @Resource
    private ShangjiaService shangjiaService;

    @Resource
    private ShangpinOrderService shangpinOrderService;

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        String role = String.valueOf(request.getSession().getAttribute("role"));
        if ("用户".equals(role))
            params.put("yonghuId", request.getSession().getAttribute("userId"));
        else if ("商家".equals(role))
            params.put("shangjiaId", request.getSession().getAttribute("userId"));
        params.put("shangpinDeleteStart", 1);
        params.put("shangpinDeleteEnd", 1);
        CommonUtil.checkMap(params);
        PageUtils page = shangpinService.queryPage(params);

        //字典表数据转换
        List<ShangpinView> list = (List<ShangpinView>) page.getList();
        for (ShangpinView c : list) {
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(c, request);
        }
        return R.ok().put("data", page);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id, HttpServletRequest request) {
        ShangpinEntity shangpin = shangpinService.selectById(id);
        if (shangpin != null) {
            //entity转view
            ShangpinView view = new ShangpinView();
            BeanUtils.copyProperties(shangpin, view);//把实体数据重构到view中
            //级联表 商家
            //级联表
            ShangjiaEntity shangjia = shangjiaService.selectById(shangpin.getShangjiaId());
            if (shangjia != null) {
                BeanUtils.copyProperties(shangjia, view, new String[]{"id", "createTime", "insertTime", "updateTime", "shangjiaId"});//把级联的数据添加到view中,并排除id和创建时间字段,当前表的级联注册表
                view.setShangjiaId(shangjia.getId());
            }
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        } else {
            return R.error(511, "查不到数据");
        }

    }

    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody ShangpinEntity shangpin, HttpServletRequest request) {
        String role = String.valueOf(request.getSession().getAttribute("role"));
        if ("商家".equals(role))
            shangpin.setShangjiaId(Integer.valueOf(String.valueOf(request.getSession().getAttribute("userId"))));

        Wrapper<ShangpinEntity> queryWrapper = new EntityWrapper<ShangpinEntity>()
                .eq("shangjia_id", shangpin.getShangjiaId())
                .eq("shangpin_name", shangpin.getShangpinName())
                .eq("shangpin_types", shangpin.getShangpinTypes())
                .eq("shangpin_kucun_number", shangpin.getShangpinKucunNumber())
                .eq("shangxia_types", shangpin.getShangxiaTypes())
                .eq("shangpin_delete", 1);

        logger.info("sql语句:" + queryWrapper.getSqlSegment());
        ShangpinEntity shangpinEntity = shangpinService.selectOne(queryWrapper);
        if (shangpinEntity == null) {
            shangpin.setShangpinClicknum(1);
            shangpin.setShangxiaTypes(1);
            shangpin.setShangpinDelete(1);
            shangpin.setInsertTime(new Date());
            shangpin.setCreateTime(new Date());
            shangpinService.insert(shangpin);
            return R.ok();
        } else {
            return R.error(511, "表中有相同数据");
        }
    }

    /**
     * 后端修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody ShangpinEntity shangpin) throws NoSuchFieldException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        if ("".equals(shangpin.getShangpinPhoto()) || "null".equals(shangpin.getShangpinPhoto())) {
            shangpin.setShangpinPhoto(null);
        }
        shangpinService.updateById(shangpin);//根据id更新
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids) {
        logger.debug("delete:,,Controller:{},,ids:{}", this.getClass().getName(), ids.toString());
        ArrayList<ShangpinEntity> list = new ArrayList<>();
        for (Integer id : ids) {
            ShangpinEntity shangpinEntity = new ShangpinEntity();
            shangpinEntity.setId(id);
            shangpinEntity.setShangpinDelete(2);
            list.add(shangpinEntity);
        }
        if (list != null && list.size() > 0) {
            shangpinService.updateBatchById(list);
        }

        return R.ok();
    }

    /**
     * 批量上传
     */
    @RequestMapping("/batchInsert")
    public R save(String fileName) {
        try {
            List<ShangpinEntity> shangpinList = new ArrayList<>();//上传的东西
            Map<String, List<String>> seachFields = new HashMap<>();//要查询的字段
            int lastIndexOf = fileName.lastIndexOf(".");
            if (lastIndexOf == -1) {
                return R.error(511, "该文件没有后缀");
            } else {
                String suffix = fileName.substring(lastIndexOf);
                if (!".xls".equals(suffix)) {
                    return R.error(511, "只支持后缀为xls的excel文件");
                } else {
                    URL resource = this.getClass().getClassLoader().getResource("static/upload/" + fileName);//获取文件路径
                    File file = new File(resource.getFile());
                    if (!file.exists()) {
                        return R.error(511, "找不到上传文件，请联系管理员");
                    } else {
                        List<List<String>> dataList = PoiUtil.poiImport(file.getPath());//读取xls文件
                        dataList.remove(0);//删除第一行，因为第一行是提示
                        for (List<String> data : dataList) {
                            //循环
                            ShangpinEntity shangpinEntity = new ShangpinEntity();
                            shangpinList.add(shangpinEntity);

                            //把要查询是否重复的字段放入map中
                            if (seachFields.containsKey("shangpinUuidNumber")) {
                                List<String> shangpinUuidNumber = seachFields.get("shangpinUuidNumber");
                                shangpinUuidNumber.add(data.get(0));//要改的
                            } else {
                                List<String> shangpinUuidNumber = new ArrayList<>();
                                shangpinUuidNumber.add(data.get(0));//要改的
                                seachFields.put("shangpinUuidNumber", shangpinUuidNumber);
                            }
                        }

                        //查询是否重复
                        //商品编号
                        List<ShangpinEntity> shangpinEntities_shangpinUuidNumber = shangpinService.selectList(new EntityWrapper<ShangpinEntity>().in("shangpin_uuid_number", seachFields.get("shangpinUuidNumber")).eq("shangpin_delete", 1));
                        if (shangpinEntities_shangpinUuidNumber.size() > 0) {
                            ArrayList<String> repeatFields = new ArrayList<>();
                            for (ShangpinEntity s : shangpinEntities_shangpinUuidNumber) {
                                repeatFields.add(s.getShangpinUuidNumber());
                            }
                            return R.error(511, "数据库的该表中的 [商品编号] 字段已经存在 存在数据为:" + repeatFields.toString());
                        }
                        shangpinService.insertBatch(shangpinList);
                        return R.ok();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(511, "批量插入数据异常，请联系管理员");
        }
    }

    /**
     * 个性推荐
     */
    @IgnoreAuth
    @RequestMapping("/gexingtuijian")
    public R gexingtuijian(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        CommonUtil.checkMap(params);
        List<ShangpinView> returnShangpinViewList = new ArrayList<>();

        //查询订单
        Map<String, Object> params1 = new HashMap<>(params);
        params1.put("sort", "id");
        params1.put("yonghuId", request.getSession().getAttribute("userId"));
        PageUtils pageUtils = shangpinOrderService.queryPage(params1);
        List<ShangpinOrderView> orderViewsList = (List<ShangpinOrderView>) pageUtils.getList();
        Map<Integer, Integer> typeMap = new HashMap<>();//购买的类型list
        for (ShangpinOrderView orderView : orderViewsList) {
            Integer shangpinTypes = orderView.getShangpinTypes();
            if (typeMap.containsKey(shangpinTypes)) {
                typeMap.put(shangpinTypes, typeMap.get(shangpinTypes) + 1);
            } else {
                typeMap.put(shangpinTypes, 1);
            }
        }
        List<Integer> typeList = new ArrayList<>();//排序后的有序的类型 按最多到最少
        typeMap.entrySet().stream().sorted((o1, o2) -> o2.getValue() - o1.getValue()).forEach(e -> typeList.add(e.getKey()));//排序
        Integer limit = Integer.valueOf(String.valueOf(params.get("limit")));
        for (Integer type : typeList) {
            Map<String, Object> params2 = new HashMap<>(params);
            params2.put("shangpinTypes", type);
            PageUtils pageUtils1 = shangpinService.queryPage(params2);
            List<ShangpinView> shangpinViewList = (List<ShangpinView>) pageUtils1.getList();
            returnShangpinViewList.addAll(shangpinViewList);
            if (returnShangpinViewList.size() >= limit) break;//返回的推荐数量大于要的数量 跳出循环
        }
        //正常查询出来商品,用于补全推荐缺少的数据
        PageUtils page = shangpinService.queryPage(params);
        if (returnShangpinViewList.size() < limit) {//返回数量还是小于要求数量
            int toAddNum = limit - returnShangpinViewList.size();//要添加的数量
            List<ShangpinView> shangpinViewList = (List<ShangpinView>) page.getList();
            for (ShangpinView shangpinView : shangpinViewList) {
                Boolean addFlag = true;
                for (ShangpinView returnShangpinView : returnShangpinViewList) {
                    if (returnShangpinView.getId().intValue() == shangpinView.getId().intValue())
                        addFlag = false;//返回的数据中已存在此商品
                }
                if (addFlag) {
                    toAddNum = toAddNum - 1;
                    returnShangpinViewList.add(shangpinView);
                    if (toAddNum == 0) break;//够数量了
                }
            }
        } else {
            returnShangpinViewList = returnShangpinViewList.subList(0, limit);
        }

        for (ShangpinView c : returnShangpinViewList)
            dictionaryService.dictionaryConvert(c, request);
        page.setList(returnShangpinViewList);
        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        CommonUtil.checkMap(params);
        PageUtils page = shangpinService.queryPage(params);

        //字典表数据转换
        List<ShangpinView> list = (List<ShangpinView>) page.getList();
        for (ShangpinView c : list)
            dictionaryService.dictionaryConvert(c, request); //修改对应字典表字段

        return R.ok().put("data", page);
    }

    /**
     * 前端详情
     */
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id, HttpServletRequest request) {
        logger.debug("detail方法:,,Controller:{},,id:{}", this.getClass().getName(), id);
        ShangpinEntity shangpin = shangpinService.selectById(id);
        if (shangpin != null) {

            //点击数量加1
            shangpin.setShangpinClicknum(shangpin.getShangpinClicknum() + 1);
            shangpinService.updateById(shangpin);

            //entity转view
            ShangpinView view = new ShangpinView();
            BeanUtils.copyProperties(shangpin, view);//把实体数据重构到view中

            //级联表
            ShangjiaEntity shangjia = shangjiaService.selectById(shangpin.getShangjiaId());
            if (shangjia != null) {
                BeanUtils.copyProperties(shangjia, view, new String[]{"id", "createDate"});//把级联的数据添加到view中,并排除id和创建时间字段
                view.setShangjiaId(shangjia.getId());
            }
            //修改对应字典表字段
            dictionaryService.dictionaryConvert(view, request);
            return R.ok().put("data", view);
        } else {
            return R.error(511, "查不到数据");
        }
    }


    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody ShangpinEntity shangpin, HttpServletRequest request) {
        logger.debug("add方法:,,Controller:{},,shangpin:{}", this.getClass().getName(), shangpin.toString());
        Wrapper<ShangpinEntity> queryWrapper = new EntityWrapper<ShangpinEntity>()
                .eq("shangjia_id", shangpin.getShangjiaId())
                .eq("shangpin_name", shangpin.getShangpinName())
                .eq("shangpin_uuid_number", shangpin.getShangpinUuidNumber())
                .eq("shangpin_types", shangpin.getShangpinTypes())
                .eq("shangpin_kucun_number", shangpin.getShangpinKucunNumber())
                .eq("shangpin_clicknum", shangpin.getShangpinClicknum())
                .eq("shangxia_types", shangpin.getShangxiaTypes())
                .eq("shangpin_delete", shangpin.getShangpinDelete())
                ;
        logger.info("sql语句:" + queryWrapper.getSqlSegment());
        ShangpinEntity shangpinEntity = shangpinService.selectOne(queryWrapper);
        if (shangpinEntity == null) {
            shangpin.setShangpinClicknum(1);
            shangpin.setShangpinDelete(1);
            shangpin.setInsertTime(new Date());
            shangpin.setCreateTime(new Date());
            shangpinService.insert(shangpin);

            return R.ok();
        } else {
            return R.error(511, "表中有相同数据");
        }
    }

}

